package com.soboot.base.util;

import com.soboot.base.model.BaseRole;
import com.soboot.base.model.BaseUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:
 * @createTime: 2022年09月19日 16:52:36
 * @version:
 * @Description:
 * @Copyright:
 */
public class SecurityUtil {

    /**
     * 获取用户
     *
     * @return user
     */
    public static BaseUser getDataUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof BaseUser) {
                BaseUser user = (BaseUser) principal;
                return user;
            }
        }
        return null;
    }

    /**
     * 获取用户ID
     *
     * @return id
     */
    public static String getUserId() {
        BaseUser user = getDataUser();
        if (user != null){
            return String.valueOf(user.getId());
        }
        return "";
    }

    /**
     * 获取用户部门
     *
     * @return id
     */
    public static String getUserDeptId() {
        BaseUser user = getDataUser();
        if (user != null){
            return user.getDeptName();
        }
        return "";
    }

    /**
     * 获取用户名称
     *
     * @return username
     */
    public static String getUserName() {
        BaseUser user = getDataUser();
        if (user != null){
            return user.getUsername();
        }
        return "";
    }

    /**
     * 获取用户昵称
     *
     * @return nickname
     */
    public static String getNickname() {
        BaseUser user = getDataUser();
        if (user != null){
            return user.getNickName();
        }
        return "";
    }

    /**
     * 获取用户角色
     *
     * @return username
     */
    public static List<String> getUserRoleIds() {
        BaseUser user = getDataUser();
        if (user != null){
            List<String> roles = user.getRoles().stream().map(BaseRole::getId).collect(Collectors.toList());
            return roles;
        }
        return null;
    }

    /**
     * 获取用户
     *
     * @return user
     */
    public static boolean isAdmin() {
        BaseUser user = getDataUser();
        if (user != null){
            return user.isAdmin();
        }
        return false;
    }
}
